define(['../../common/service', './userAudienceKit', '../../common/copybox', '../feed/feed'],
    function(http,userAudienceKit, CB,feed){
    var audienceManager = {
        actions : [{'id' : 'ViewContent', 'text': 'Viewed'},{'id' : 'AddToCart', 'text': 'Added to cart'},{'id' : 'Purchase', 'text': 'Purchased'}],
        retention_seconds_unit : 24 * 60 * 60,
       weFeedId : window.localStorage.getItem('weFeedId'),
        init : function(){
            var _this = this;
            feed._init_tabs(4);
            //初始化列表
            $('table[list-manager="audienceManagerList"]').listManager('init',{
                setTopVal:173,//调整吸顶的高度,需要减去这个高度
                scrollDOM:$('.fmp-article')//监听滚动条
                ,supportAjaxPage: true
                ,pageCallback:function(query){
                    _this.query = query;
                    _this.getList(query);
                }
            }, function(query){
                _this.query = query;
                _this.getList(query);
            });
            _this.bindEvent();
        },
        bindEvent : function() {
            var _this = this;
            $(".createAudience").off("click").on("click", function(e){
                var _createAudienceModal = $("#create-audience");
                var param = {
                    WeFeedId : _this.weFeedId
                }
                http.work('/useraudiences/validateProductSetList',param, "POST").then(function(res){
                    if (res.flag == 'success'){

                        var _data = res.data;
                        //如果没账号或产品系列需要提示
                        if (!_data.account){
                            _this.showCreateModal(1);
                            return false;
                        }

                        if (!_data.productSets || !_data.productSets.length){
                            _this.showCreateModal(2);
                            return false;
                        }

                        $.each(_data.productSets, function(i, _product){
                            _product.id = _product.productSetId;
                            _product.text = _product.productSetName;
                        })

                        _this.verify_audience_account = _data.account;
                        _this.verify_audience_productset = _data.productSets;
                        _this.showCreateModal(3);
                    } else {
                       // Kit.loading.hide($("#create-audience"));
                    }


                }).done(function(){
                    $("#create-audience").find(".modal-title").html("创建受众");
                })



            })

            _this.initCreateModal();
            _this.initVerifyModal();
            _this.viewAudience();
        },
        showCreateModal : function(_isCreate, _viewAudience){
            var _this = this;
            //查询初始化信息
            var _createAudienceModal = $("#create-audience");
            _createAudienceModal.find(".modal-body").html($("#t-create-audience-content").html());
            _createAudienceModal.find(".useraudience-success").addClass("hide");
            if (_isCreate == 4){
                //查看受众
                _createAudienceModal.find(".modal-body").removeClass("disable-c");
                _createAudienceModal.find(".a-m-c").removeClass("hide");
                _createAudienceModal.find(".disable-content").addClass("hide");
                _createAudienceModal.find(".generate-btn").addClass("hide");
                _createAudienceModal.find(".ok-btn").addClass("hide");
            } else if (_isCreate == 3){
                //创建受众
                _createAudienceModal.find(".modal-body").removeClass("disable-c");
                _createAudienceModal.find(".a-m-c").removeClass("hide");
                _createAudienceModal.find(".disable-content").addClass("hide");
                _createAudienceModal.find(".generate-btn").removeClass("hide");
                _createAudienceModal.find(".ok-btn").removeClass("hide").addClass("disabled");
            } else if (_isCreate == 2){
                //账号未授权
                _createAudienceModal.find(".modal-body").addClass("disable-c");
                _createAudienceModal.find(".a-m-c").addClass("hide");
                _createAudienceModal.find(".disable-content").find(".go-account").addClass("hide");
                _createAudienceModal.find(".disable-content").find(".go-product-set").removeClass("hide");
                _createAudienceModal.find(".disable-content").removeClass("hide");
                _createAudienceModal.find(".generate-btn").addClass("hide");
                _createAudienceModal.find(".ok-btn").addClass("hide");
            } else if (_isCreate == 1){
                //adset未授权
                _createAudienceModal.find(".modal-body").addClass("disable-c");
                _createAudienceModal.find(".a-m-c").addClass("hide");
                _createAudienceModal.find(".disable-content").find(".go-account").removeClass("hide");
                _createAudienceModal.find(".disable-content").find(".go-product-set").addClass("hide");
                _createAudienceModal.find(".disable-content").removeClass("hide");
                _createAudienceModal.find(".generate-btn").addClass("hide");
                _createAudienceModal.find(".ok-btn").addClass("hide");
            }

            _this.viewAudienceModal = _viewAudience;
            $("#create-audience").modal("show");

        },
        viewAudience : function(){
            var _this = this;
            var list_M = $("table[list-manager='audienceManagerList']");
            list_M.off("click", ".view-audience").on("click", ".view-audience", function(e){
                var audience = $(this).parents("tr").data("audience");

                http.do("/useraudiences/findById",{id :audience.id}, "GET").then(function(res){
                    if (res.flag == 'success'){
                        $("#create-audience").find(".modal-title").html("查看受众");
                        $("#create-audience").find(".ok-btn").addClass("hide");
                        $("#create-audience").find(".generate-btn").addClass("hide");
                        _this.showCreateModal(4, res.data);
                    } else {
                        Kit.alert2(res.msg || "查看受众失败")
                    }
                }, function(res){
                    Kit.alert2( "查看受众失败")
                })
            })
        },
        renderCustomAudience : function(){
            $("div.ndp-drop-wrapper[name=customaudience-clude]").empty().drop({
                data:[{name : I18N.getText('audienceManager', 'include'), val : '1'},{name :I18N.getText('audienceManager', 'exclude'), val :'0'}],
                caret:"glyphicon-menu-right"
            }).val({name : I18N.getText('audienceManager', 'include'), val : '1'});

            $(".customaudience",'#create-audience').empty().select2({
                data: [],
                placeholder: I18N.getText('management', 'chooseCustomAudience'),
                multiple: true,
                allowClear: false,
                width: '100%',
                templateSelection : function(_customAudience){
                    return _customAudience.name  + '[' + (_customAudience.isClude == 1  || _customAudience.isClude == "1" ? I18N.getText('management', 'include') : I18N.getText('management', 'exclude'))+ ']';
                }
            }).off("select2:unselect").on("select2:unselect",function(e){
            }).off("select2:select").on("select2:select",function(e){
                var selects = $(".customaudience").select2("data");
                var o = e.params.data
                var index = Kit.keyIn(selects, o.id, "id")
                if (index > -1) {
                    selects[index]["isClude"] = $("div.ndp-drop-wrapper[name=customaudience-clude]").data("val");
                    $(".customaudience").select2("data", selects);
                }
            });
        },
        renderLocation: function () {
            var _this = this;
             //地区
            $("div.ndp-drop-wrapper[name=location_types]", '#create-audience').drop({
                data: [{
                    name: I18N.getText('createAd', 'peopleAllHere'),
                    val: '1'
                }, {name: I18N.getText('createAd', 'peopleLiveInHere'), val: '2'},
                    {
                        name: I18N.getText('createAd', 'peopleRecentlyHere'),
                        val: '3'
                    }, {name: I18N.getText('createAd', 'peopleTravelingHere'), val: '4'}],
                caret: "glyphicon-menu-right"
            }).on("ITEM_CHANGE", function (e) {
            }).val({name: I18N.getText('createAd', 'peopleAllHere'), val: '1'})

            var _isClude = 1;
            $("div.ndp-drop-wrapper[name=location-clude]", '#create-audience').drop({
                data: [{
                    name: I18N.getText('audienceManager', 'include'),
                    val: '1'
                }, {name: I18N.getText('audienceManager', 'exclude'), val: '0'}],
                caret: "glyphicon-menu-right"
            }).on("ITEM_CLICK", function (e) {
                _isClude = e.originalEvent.data.val;
            }).val({name: I18N.getText('audienceManager', 'include'), val: '1'})

            var _cType = 'country';
            $("div.ndp-drop-wrapper[name=location-type]", '#create-audience').drop({
                data: [{
                    name: I18N.getText('audienceManager', 'country'),
                    val: 'country'
                }, {name: I18N.getText('audienceManager', 'all'), val: 'all'}],
                caret: "glyphicon-menu-right"
            }).on("ITEM_CLICK", function (e) {
                _cType = e.originalEvent.data.val;
            }).val({name: I18N.getText('audienceManager', 'country'), val: 'country'})

            userAudienceKit.initLocation({
                locationArea: $(".location-area", '#create-audience'),
                changeCallBack: function () {
                    _this.countLocation();
                }
            });
        },
        initCreateModal : function (){
            var _this = this;
            //todo
            var _createAudience = $("#create-audience");
            _createAudience.modal({
                backdrop: 'static',
                keyboard: false,
                show:false
            });

            _createAudience.on('show.bs.modal', function (e) {
                _createAudience.find(".verify-tip").empty();

                //規則
                _this.renderAudienceRule();

                //版位
                _this.renderPageType();

                //自定义受众
                _this.renderCustomAudience();

                //地区
                _this.renderLocation();

                //初始化年龄
                userAudienceKit.initAge({
                    container : $("#create-audience")
                })

                if (_this.viewAudienceModal){
                    _this.fillAudience(_this.viewAudienceModal);
                }
            })


            _createAudience.off("click", ".go-account button").on("click", ".go-account button", function(e){
                $("#create-audience").modal("hide");
                window.location.href = "#!adPublishCondition";
                location.reload();
            })
            _createAudience.off("click", ".go-product-set button").on("click", ".go-product-set button", function(e){
                $("#create-audience").modal("hide");
                window.location.href = "#!sets";
                location.reload();
            })

            //校验受众
            _createAudience.find(".generate-btn").off("click").on("click", function(e){
                if ($(this).hasClass("disabled")){
                    return false;
                }

                //清楚错误信息
                _this.clearVerify();

                //先校验用户条件
                var targeting_spec = {};
                if (!verify(targeting_spec)){
                    return false;
                }

                //年龄
                targeting_spec.age_min = $("div.ndp-drop-wrapper[name=min-age]", "#create-audience").data("val");
                targeting_spec.age_max = $("div.ndp-drop-wrapper[name=max-age]", "#create-audience").data("val");

                //性别
                var _gender = $('input[name="gender"]:checked', "#create-audience").val()
                if ('0' != _gender){
                    targeting_spec.genders = [_gender];
                }

                _this.create_targeting_spec = targeting_spec;
                console.log(targeting_spec)
                if (!_this.weFeedId){
                    Kit.alert("error", I18N.getText('audienceManager', 'timeoutR'))
                    return false;
                }
                //从后台获取可以用于校验的产品
                Kit.loading.show($("#create-audience"), null, null ,true);
                var _verifyModal = $("#verify-audience");
                //var param = {
                //    WeFeedId : _this.weFeedId
                //}
                //http.work('/useraudiences/validateProductSetList',param, "POST").then(function(res){
                //    if (res.flag == 'success'){
                //        var _data = res.data;
                //        var _verifyAudienceModal = $("#verify-audience");
                //        //如果没账号或产品系列需要提示
                //        if (!_data.account){
                //            _verifyAudienceModal.find(".modal-body").addClass("disable-c");
                //            _verifyAudienceModal.find(".verify-audience-c").addClass("hide");
                //            _verifyAudienceModal.find(".ok-btn").addClass("disabled");
                //            _verifyAudienceModal.find(".disable-content").find(".go-account").removeClass("hide");
                //            _verifyAudienceModal.find(".disable-content").find(".go-product-set").addClass("hide");
                //            _verifyAudienceModal.find(".disable-content").removeClass("hide");
                //            return false;
                //        }
                //
                //        if (!_data.productSets || !_data.productSets.length){
                //            _verifyAudienceModal.find(".modal-body").addClass("disable-c");
                //            _verifyAudienceModal.find(".verify-audience-c").addClass("hide");
                //            _verifyAudienceModal.find(".ok-btn").addClass("disabled");
                //            _verifyAudienceModal.find(".disable-content").find(".go-account").addClass("hide");
                //            _verifyAudienceModal.find(".disable-content").find(".go-product-set").removeClass("hide");
                //            _verifyAudienceModal.find(".disable-content").removeClass("hide");
                //            return false;
                //        }
                //        _verifyAudienceModal.find(".ok-btn").removeClass("disabled");
                //        _verifyAudienceModal.find(".modal-body").removeClass("disable-c");
                //        _verifyAudienceModal.find(".disable-content").addClass("hide");
                //        _verifyAudienceModal.find(".verify-audience-c").removeClass("hide");
                //
                //        $.each(_data.productSets, function(i, _product){
                //            _product.id = _product.productSetId;
                //            _product.text = _product.productSetName;
                //        })
                //
                //        _this.verify_audience_account = _data.account;
                //        //渲染
                //        _verifyAudienceModal.find(".v-p-c").html('<div class="ndp-drop-wrapper verify-audience-p" name="verify-audience-p"></div>');
                //        _verifyAudienceModal.find("div.ndp-drop-wrapper[name=verify-audience-p]").empty().drop({
                //            data : _data.productSets,
                //            placeholder: I18N.getText('audienceManager', 'selectProductSetR'),
                //            caret: "glyphicon-menu-right"
                //        })
                //    } else {
                //        Kit.loading.hide($("#create-audience"));
                //    }
                //
                //
                //}).done(function(){
                //    _verifyModal.modal("show");
                //})

                _verifyModal.find(".v-p-c").html('<div class="ndp-drop-wrapper verify-audience-p" name="verify-audience-p"></div>');
                _verifyModal.find("div.ndp-drop-wrapper[name=verify-audience-p]").empty().drop({
                    data : _this.verify_audience_productset,
                    placeholder: I18N.getText('audienceManager', 'selectProductSetR'),
                    caret: "glyphicon-menu-right"
                })
                _verifyModal.modal("show");

            })

            function verify(_targeting_spec){
                var flag = true;
                if (!verifyRules(_targeting_spec)){
                    return false;
                }

                //版位
                if (!verifyPageType(_targeting_spec)){
                    return false;
                }

                if (!verifyLocations(_targeting_spec)){
                    return false;
                }

                return true;
            }

            function verifyPageType(_targeting_spec){
                var page_types = [];
                $.each($('input[name="page-type"]:checked', "#create-audience"), function(i, page_type){
                    page_types.push($(page_type).val());
                })

                if (page_types.length == 0){
                    _this.showDangerTip("warning", I18N.getText('audienceManager', 'selectPlacement'));
                    return false;
                }

                _targeting_spec.page_types = page_types;
                return true;
            }

            function verifyRules(_targeting_spec){
                var flag = true;
                var rules = $(".rule-item", "#create-audience").find(".range-c");
                var inclusions = [];
                var exclusions = [];

                $.each(rules, function(i, _rule){
                    var actions = $(_rule).find(".actions").select2("data");
                    if (actions.length){
                        var _minE = $(_rule).find('input[name="min"]');
                        var _minv = _minE.val();
                        if (_minv == ''){
                            _minE.addClass("form-input-warning").addClass("can-clear");
                            _this.showDangerTip("warning", I18N.getText('audienceManager', 'minReminder'));
                            flag = false;
                            return false;
                        }
                        var _min_retention_seconds = Number(_minv) * _this.retention_seconds_unit;

                        var _maxE = $(_rule).find('input[name="max"]');
                        var _maxv = _maxE.val();
                        var _max_retention_seconds = _maxv == '' ? 0 :( Number(_maxv) * _this.retention_seconds_unit);

                        if (Number(_minv) < 1 || Number(_minv) > 180){
                            _minE.addClass("form-input-warning").addClass("can-clear");
                            $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                            flag = false;
                            return false;
                        }

                        if (_maxv != '' && (Number(_maxv) < 1 || Number(_maxv) > 180)){
                            _maxE.addClass("form-input-warning").addClass("can-clear");
                            $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                            flag = false;
                            return false;
                        }

                        if (_maxv != '' && _min_retention_seconds >= _max_retention_seconds){
                            $(_rule).find(".i-range-r").addClass("can-clear-r").removeClass("hide").html(I18N.getText('audienceManager', 'nearFarR'))
                            flag = false;
                            return false;
                        }

                        $.each(actions, function(i, _action_o){
                            if (_action_o.isClude == 1 || _action_o.isClude == '1'){
                                //包括
                                if (_max_retention_seconds == 0){
                                    inclusions.push({
                                        "retention_seconds" : _min_retention_seconds,
                                        "rule" : {
                                            "event" : {
                                                "eq" : _action_o.id
                                            }
                                        }})
                                } else {
                                    inclusions.push({
                                        "retention_seconds" : _max_retention_seconds,
                                        "rule" : {
                                            "event" : {
                                                "eq" : _action_o.id
                                            }
                                        }});

                                    exclusions.push({
                                        "retention_seconds" : _min_retention_seconds,
                                        "rule" : {
                                            "event" : {
                                                "eq" : _action_o.id
                                            }
                                        }})
                                }
                            } else {
                                exclusions.push({
                                    "retention_seconds" : _max_retention_seconds == 0 ? _min_retention_seconds : _max_retention_seconds,
                                    "rule" : {
                                        "event" : {
                                            "eq" : _action_o.id
                                        }
                                    }})
                            }
                        })
                    }
                });

                if (!flag){
                    return false;
                }

                if (inclusions.length == 0){
                    _this.showDangerTip("warning", I18N.getText('audienceManager', 'actionReminder'));
                    flag = false;
                    return false;
                }

                var product_audience_specs = {
                    inclusions : inclusions
                }

                if (exclusions.length){
                    product_audience_specs.exclusions = exclusions;
                }

                _targeting_spec.product_audience_specs = [product_audience_specs];

                return flag;
            }

            function verifyLocations(_targeting_spec){
                var  locationResults = userAudienceKit.buildLocation({"locationArea" : $(".location-select2", "#create-audience")} )

                var geo_locations = locationResults.geo_locations;
                var excluded_geo_locations = locationResults.excluded_geo_locations;
                if (!geo_locations){
                    _this.showDangerTip("warning", I18N.getText('audienceManager', 'oneLocation'));
                    return false;
                }

                if (geo_locations){
                    _targeting_spec.geo_locations = geo_locations;
                    //地区类型
                    var _locationTypes = $("div.ndp-drop-wrapper[name=location_types]", "#create-audience").data("val");
                    if (_locationTypes == 1){
                        //这个地区所有人
                        geo_locations.location_types = ["home","recent"];
                    } else if (_locationTypes == 2){
                        //在这里居住的用户
                        geo_locations.location_types = ["home"];
                    } else if (_locationTypes == 3){
                        //最近到过这里的用户
                        geo_locations.location_types = ["recent"];
                    } else {
                        //在这里旅游的用户
                        geo_locations.location_types = ["travel_in"];
                    }

                }

                if (excluded_geo_locations){
                    _targeting_spec.excluded_geo_locations = excluded_geo_locations;
                }

                return true;
            }

            //创建受众魔板
            _createAudience.find(".ok-btn").off("click").on("click", function(e){
                if ($(this).hasClass("disabled")){
                    return false;
                }

                //清除校验信息
                _this.clearVerify();
                //受众模板名称 一定要填写
                var _nameE = _createAudience.find('input[name="audience-name"]');
                var _name = $.trim(_nameE.val());
                if ('' == _name){
                    _nameE.addClass("form-input-warning").addClass("can-clear");;
                    _this.showDangerTip("warning", I18N.getText('audienceManager', 'enterAudienceR'));
                    return false;
                }

                var param = {
                    weFeedId : _this.create_product.feedId,
                    fbAccountId : _this.verify_audience_account.fbAccountId,
                    productCatalogId : _this.create_product.catalogId,
                    productSetId : _this.create_product.productSetId,
                    name : _name,
                    localTargeting : _this.buildLocalTargeting(),
                    fbTargeting : _this.finalTarging,
                    potentialUser : _this.potentialUser
                }
                http.work('/useraudiences/save',param,'POST').then(function(res){
                    if (res.flag == "success"){
                        _createAudience.modal("hide");
                        location.reload();
                    } else {
                        _this.showDangerTip("danger", res.msg || I18N.getText('audienceManager', 'createAudienceFail'));
                    }
                })
            })
        },
        fillAudience : function(_viewAudience){
            var _this = this;
            var _localTargeting =  JSON.parse(_viewAudience.localTargeting);
            var cAModal = $("#create-audience");
            //回填规则
            if (_localTargeting.rules && _localTargeting.rules.length) {
                $.each(_localTargeting.rules, function(i, _rule){
                    if (i != 0){
                        cAModal.find(".btn-plus").trigger('click');
                    }

                    var _cbox = $('.cbox', ".rule-item").eq(i);
                    _cbox.find('input[name="min"]').val(_rule.min || '');
                    _cbox.find('input[name="max"]').val(_rule.max || '');
                    //行为
                    if (_rule.actions || _rule.actions.length){
                        var _ce = _cbox.find('.actions');
                        $.each(_rule.actions, function(i, _action){
                            _cbox.find('.actions').find("option[value='" +  _action.id  +  "']").remove();

                            //选了某一个后其他的不能选
                            $.each($(".rule-item", "#create-audience").find(".actions"), function(i, _e){
                                if (_ce[0] != this){
                                    $(_e).find('option[value="' + _action.id  + '"]').remove();
                                }
                            })
                        })

                        _cbox.find('.actions').select2("data", _rule.actions);

                    }
                })
            }

            //回填版位
            if (_localTargeting.page_types && _localTargeting.page_types.length){
                $.each(_localTargeting.page_types, function(i, _page_type){
                    cAModal.find('input[value="' + _page_type +  '"]').prop("checked", "checked");
                })
                _this.canAdd(cAModal);
            }

            //回填自定义受众
            if (_localTargeting.customAudiences && _localTargeting.customAudiences.length){
                cAModal.find(".customaudience").select2("data", _localTargeting.customAudiences);
            }
            //回填地区
            if (_localTargeting.location){
                var _locationType = _localTargeting.location.locationType;
                var _locationTypesE = cAModal.find("div.ndp-drop-wrapper[name=location_types]");
                if (_locationType == 1 ){
                    _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleAllHere'), val : '1'});
                } else {
                    if (_locationType == 2){
                        _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleLiveInHere'), val : '2'});
                    }

                    if (_locationType == 3){
                        _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleRecentlyHere'), val : '3'});
                    }

                    if (_locationType == 4){
                        _locationTypesE.drop('val', {name : I18N.getText('createAd', 'peopleTravelingHere'), val : '4'});
                    }
                }

                cAModal.find(".location-select2").select2("data", _localTargeting.location.locations);
            }

            //回填年龄
            if (_localTargeting.age){
                cAModal.find("div.ndp-drop-wrapper[name=min-age]").drop('val',
                    {name : _localTargeting.age.age_min, val : _localTargeting.age.age_min});

                cAModal.find("div.ndp-drop-wrapper[name=max-age]").drop('val',
                    {name : _localTargeting.age.age_max, val : _localTargeting.age.age_max});
            }

            //回填性别
            if (_localTargeting.gender){
                cAModal.find('input[name="gender"][value="' + _localTargeting.gender + '"]').prop("checked", "checked");
            }

            //名称
            cAModal.find('input[name="audience-name"]').val(_viewAudience.name || '');

        },
        canAdd : function (_container){
            var _this = this;
            var selectedNum = 0;
            var actionsGroups = _container.find(".rule-item").find(".actions");
            var _num;
            $.each(actionsGroups, function(i, _actitons){
                _num = $(_actitons).select2("data").length;
                if (_num == 0){
                    _num += 1;
                }
                selectedNum += _num ;
            })
            if ((_this.actions.length - selectedNum) < 1){
                _container.find('.btn-plus').addClass("hide");
            } else {
                _container.find('.btn-plus').removeClass("hide");
            }
        },
        buildLocalTargeting : function(){
            var localTargeting = {};
            //规则
            var rules = [];
            var ruleEs = $(".rule-item", "#create-audience").find(".range-c");
            $.each(ruleEs, function(i, ruleE) {
                var actions = $(ruleE).find(".actions").select2("data");
                if (actions.length) {
                    var _min = $(ruleE).find('input[name="min"]').val()
                    var _max = $(ruleE).find('input[name="max"]').val()
                    rules.push({
                        min : _min,
                        max : _max,
                        actions : actions
                    })
                }
            });
            localTargeting.rules =  rules;

            //版位
            var page_types = [];
            $.each($('input[name="page-type"]:checked', "#create-audience"), function(i, page_type){
                page_types.push($(page_type).val());
            })

            localTargeting.page_types = page_types;
            //地区
            var selectLocations = $(".location-select2", "#create-audience").select2("data");
            localTargeting.location = {
                locationType : $("div.ndp-drop-wrapper[name=location_types]", "#create-audience").data("val"),
                locations : selectLocations
            }
            //年龄
            localTargeting.age = {
                age_min : $("div.ndp-drop-wrapper[name=min-age]", "#create-audience").data("val"),
                age_max : $("div.ndp-drop-wrapper[name=max-age]", "#create-audience").data("val"),
            }

            //性别
            localTargeting.gender = $('input[name="gender"]:checked', "#create-audience").val();
            console.log(localTargeting)
            return localTargeting;
        },
        clearVerify : function(){
            $(".can-clear").removeClass("form-input-warning").removeClass("can-clear");
            $(".verify-tip").empty();
            $(".can-clear-r").removeClass("can-clear-r").addClass("hide");
        },
        showDangerTip : function(_type, _content){
            showTip({
                bind:$('#create-audience').find(".verify-tip"),
                time:null,
                type:_type,
                icon:"<i class='glyphicon glyphicon-alert'></i>",
                content:_content,
                through:true,
                close:true
            });
        },
        initVerifyModal : function(){
            var _this = this;
            var _verifyModal = $("#verify-audience");
            _verifyModal.modal({
                backdrop: 'static',
                keyboard: false,
                show:false
            });

            _verifyModal.on('show.bs.modal', function (e) {
                _this.clearVerify();
            })

            _verifyModal.on('hide.bs.modal', function (e) {
                Kit.loading.hide($("#create-audience"));
            })

            _verifyModal.find(".ok-btn").off("click").on("click", function(e){
                if ($(this).hasClass("disabled")){
                    return false;
                }
                //清除原来校验的情况
                _this.clearVerify();
                //产品必选
                var pE = _verifyModal.find("div.ndp-drop-wrapper[name=verify-audience-p]");
                var p = pE.drop("data");
                if (!p.id){
                    pE.addClass("form-input-warning").addClass("can-clear");
                    $(".warning-r[for='verify-audience-p']").addClass("can-clear-r").removeClass("hide");
                    return false;
                }
                var _createAudience = $("#create-audience");
                _createAudience.find(".generate-btn").addClass("disabled");
                _createAudience.find(".useraudience-success").addClass("hide");
                _createAudience.find(".ok-btn").addClass("disabled");

                _this.create_targeting_spec.product_audience_specs[0].product_set_id = p.fbProductSetId;
                _this.finalTarging = _this.create_targeting_spec;
                _this.create_product = p;
                var par = {
                    targeting_spec : _this.create_targeting_spec,
                    account_id : _this.verify_audience_account.fbAccountId
                };
                http.work('/useraudiences/previewSimpleUserAudience', par, 'POST').then(function(res){
                    if(res.flag == 'success') {
                        setTimeout(function(){
                            _this.keepCalling(res.data.userAudienceCacheId);
                        },200)
                    } else {
                        _this.useraudienceError(res.msg);
                    }
                },function(err){
                    _this.useraudienceError(I18N.getText('management', 'generateAudienceFailed'));
                })

                _verifyModal.modal("hide");
            })
            //
            //_verifyModal.find("a", ".go-account").off("click").on("click", function(e){
            //    $("#create-audience").modal("hide");
            //    location.reload();
            //})
            //_verifyModal.find("a", ".go-product-set").off("click").on("click", function(e){
            //    $("#create-audience").modal("hide");
            //    window.location.href = "#!sets";
            //    //location.reload();
            //})
        },
        keepCalling : function(_userAudienceCacheId){
            var _this = this;
            var par = {
                userAudienceCacheId : _userAudienceCacheId
            }
            http.work('/useraudiences/searchPreviewSimpleUserAudienceResult', par, 'POST').then(function(res){
                if(res.flag == 'success') {
                    var da = res.data;
                    if(da.isComplete){
                        //完成
                        $(".generate-btn").removeClass("disabled");
                        var people = da.previewUserAudienceResults && da.previewUserAudienceResults[0] && da.previewUserAudienceResults[0].people
                            ? da.previewUserAudienceResults[0].people : 0;
                        if (people > 0){
                            _this.potentialUser = people;
                            $("#create-audience").find(".useraudience-success").removeClass("hide").find("span").html(Kit.toThousands(people));
                            $("#create-audience").find(".ok-btn").removeClass("disabled");
                        } else {
                            console.log("生成用户定位失败");
                            var _msg = "【" + I18N.getText('management', 'generateAudienceFailed') + "】";
                            if (da.previewUserAudienceResults[0].exception){
                                console.log(da.previewUserAudienceResults[0].exception)
                                var _exception = JSON.parse(da.previewUserAudienceResults[0].exception);
                                if (_exception["error"] &&  _exception["error"]["error_data"] && _exception["error"]["error_data"]["showable_errors"]&& _exception["error"]["error_data"]["showable_errors"].length > 0){
                                    _msg += _exception["error"]["error_data"]["showable_errors"][0];
                                } else {
                                    _msg = da.previewUserAudienceResults[0].exception;
                                }
                            }
                            _this.useraudienceError(_msg);
                        }
                    } else {
                        setTimeout(function(){_this.keepCalling(_userAudienceCacheId) },200)   ;//返回数据不成功，再去请求，100毫秒后 直到成功为止
                    }
                }
            },function(err){
            })
    },
        useraudienceError : function(_msg){
            var _this = this;
            $(".useraudience-success ").addClass("hide");
            $(".generate-btn").removeClass("disabled");
            _this.finalTarging = null;
            _this.showDangerTip("danger", _msg);
        },
        renderAudienceRule : function(_rules){
            var _this = this;
            var _html = '<div class="range-c cbox">' +
                '<div>' +
                '<label class="s-item-title">' + I18N.getText('audienceManager', 'lastDays') + '</label>' +
                '<div class="s-item-content">' +
                '<input class="i-range form-input" name="min" style="margin-right:10px"/> '
                +  I18N.getText('audienceManager', 'to')
                + ' <input class="i-range form-input" name="max" style="margin-left:10px;margin-right:10px"/> ' + I18N.getText('audienceManager', 'days') +
                '<span class="warning-r i-range-r" for="i-range"></span>'+
                '</div>' +
                '</div>' +
                '<div class="action-c">' +
                '<div class="ndp-drop-wrapper action-i" name="action-i"></div>' +
                '<div class="action-s">' +
                '<select class="actions" style="width:100%"></select>' +
                '</div>' +
                '</div>' +
                '<a href="javascript:void(0);" cb-del="" class="close closeBtn" style="display: block;">×</a>' +
                '</div>';
            var cb = new CB.CopyBox($("#create-audience").find('.rule-item'), {
                box: _html
                ,perInit: function($box) {
                    //规则
                    $box.find("div.ndp-drop-wrapper[name=action-i]").drop({
                        data:[{name : I18N.getText('audienceManager', 'include'), val : '1'},{name :I18N.getText('audienceManager', 'exclude'), val :'0'}],
                        caret:"glyphicon-menu-right"
                    }).val({name : I18N.getText('audienceManager', 'include'), val : '1'});

                    //日期只能输整数
                    $box.find('.i-range').numeral({'scale': 0});
                    $box.find('.i-range').off("input").on("input", function(){
                        var _v = $(this).val();
                        if (_v != '' && (Number(_v) < 1 || Number(_v) > 180)){
                            $(this).addClass("form-input-warning");
                            $box.find(".i-range-r").removeClass("hide").html(I18N.getText('audienceManager', 'dataRangeR'))
                            return false;
                        }

                        var _min = $box.find('input[name="min"]').val();
                        var _max = $box.find('input[name="max"]').val();
                        if (_max != '' && Number(_min) >= Number(_max)){
                            $($box).addClass("form-input-warning");
                            $box.find(".i-range-r").removeClass("hide").html(I18N.getText('audienceManager', 'nearFarR'))
                            return false;
                        }

                        $box.find(".i-range-r").addClass("hide");
                        $(this).removeClass("form-input-warning");
                        $($box).removeClass("form-input-warning");
                    });

                    var _ce = $box.find(".actions");

                    $box.find(".actions").select2({
                        multiple: true,
                        placeholder:I18N.getText('audienceManager', 'selectActionR'),
                        data : _this.actions,
                        templateSelection : function(_actionI){
                            var _text = _actionI.text;
                            return _text  + '[' + (_actionI.isClude == 1 || _actionI.isClude == '1' ? I18N.getText('audienceManager', 'include') :I18N.getText('audienceManager', 'exclude'))+ ']';
                        }
                    }).off("select2:select").on("select2:select", function(e){
                        var o = e.params.data;
                        //选了某一个后其他的不能选
                        $.each($(".rule-item", "#create-audience").find(".actions"), function(i, _e){
                            if (_ce[0] != this){
                                $(_e).find('option[value="' + o.id  + '"]').remove();
                            }
                        })
                        canAdd();

                        var selects = $(_ce).select2("data");
                        var o = e.params.data
                        var index = Kit.keyIn(selects, o.id, "id")
                        if (index > -1) {
                            selects[index]["isClude"] = $box.find("div.ndp-drop-wrapper[name=action-i]").data('val');
                            $(_ce).select2("data", selects);
                        }
                    }).on("select2:unselect", function(e){
                        var o = e.params.data;
                        //删除后可继续选
                        $.each($(".rule-item", "#create-audience").find(".actions"), function(i, _e){
                            if (_ce[0] != this){
                                $(_e).append('<option value="' +  o.id  + '">' + o.text + '</option>');
                            }
                        })
                        canAdd();
                    })

                    //将已选的数据剔除
                    var selects = selectedActions();
                    $.each(selects, function(i, _select){
                        $(_ce).find('option[value="' + _select.id  + '"]').remove();
                    })
                }
                ,afterAdd: function($box) {
                    //由于每种行为只能选择一次，故能增加的组数最多为行为数减去当前已选行为
                    canAdd();
                }
                ,beforeRemove : function($box){
                    //将已删的数据重新补回来
                    var _ce = $box.find(".actions");
                    var deleteds = $(_ce).select2("data");
                    $.each($(".rule-item", "#create-audience").find(".actions"), function(i, _e){
                        if (_ce[0] != this){
                            $.each(deleteds, function(i, _delete){
                                $(_e).append('<option value="' +  _delete.id  + '">' + _delete.text + '</option>');
                            })
                        }
                    })

                }
                ,afterRemove:function($box){
                    canAdd();
                }
            });
            cb.init();
            var _createAudienceModal = $("#create-audience");
            _createAudienceModal.off('click', '.btn-plus').on('click', '.btn-plus', function() {
                cb.add();
            });

            function selectedActions(){
                var selects = [];
                $.each($(".rule-item", "#create-audience").find(".actions"), function(i, _e) {
                    selects = selects.concat($(_e).select2("data"));
                })
                return selects;
            }

            function canAdd(){
                var _createAudienceModal = $("#create-audience");
                var selectedNum = 0;
                var actionsGroups = _createAudienceModal.find(".rule-item").find(".actions");
                var _num;
                $.each(actionsGroups, function(i, _actitons){
                    _num = $(_actitons).select2("data").length;
                    if (_num == 0){
                        _num += 1;
                    }
                    selectedNum += _num ;
                })
                if ((_this.actions.length - selectedNum) < 1){
                    _createAudienceModal.find('.btn-plus').addClass("hide");
                } else {
                    _createAudienceModal.find('.btn-plus').removeClass("hide");
                }
            }
        },
        renderPageType : function(){
            $("#create-audience").off("click",'input[name="page-type"]').on("click",'input[name="page-type"]', function(){
                //移动应用受众网络版位依赖于移动版动态消息版位
                if ($(this).val() == 'mobilefeed' && !$(this).prop('checked')){
                    $('input[name="page-type"][value="mobileexternal"]', '#create-audience').attr("checked",false);
                    $('input[name="page-type"][value="mobileexternal"]', '#create-audience').prop("checked",false);
                }

                if ($(this).val() == 'mobileexternal' && $(this).prop('checked')){
                    $('input[name="page-type"][value="mobilefeed"]', '#create-audience').attr("checked",true);
                    $('input[name="page-type"][value="mobilefeed"]', '#create-audience').prop("checked",true);
                }
            })
        },
        countLocation : function(){
            //var self = this;
            //var flag = true;
            //var locations = $(".location-select2", "#create-audience").select2("data");
            //if (locations.length > 25){
            //    flag = false;
            //    $(".edit-tip").addClass("location-tip");
            //    self.showDangerTip("danger", I18N.getText("management", "locationLimit",  25, locations.length));
            //} else {
            //    $(".location-tip").empty();
            //    $(".edit-tip").removeClass("location-tip");
            //}
            //return flag;
        },
        getList : function(_query){
            var _this = this;
            if (!_query.pSize){
                _query.pSize = 20;
            }
            if (!_this.weFeedId){
                return false;
            }

            _query.weFeedId = _this.weFeedId;

            var loadingArea = $('.fmp-container');
            Kit.loading.show(loadingArea);
            var  _table = $('table[list-manager="audienceManagerList"]'),
                _tbody = _table.find("tbody");
            _tbody.empty();

            http.work('/useraudiences/listByFeed',_query,'POST').then(function(res){
                if (res.flag == 'success'){
                    var _list = res.data.list,
                        _paginator = res.data.paginator,
                        _serial = 0;		//序号
                    for(var i=0; i< _list.length; i++){
                        _serial = (_paginator.cPage-1) * _paginator.pSize +i + 1;
                        _tbody.append(_this.generateHTML(_list[i],_serial));
                    }

                    _table.listManager([{'resetTd':false, 'resetPageData': _paginator}]);
                    $(window).trigger('resize');
                } else {
                    Kit.alert2(res.msg || I18N.getText('audienceManager','queryFailed'))
                }
            }).done(function(){
                Kit.loading.hide(loadingArea);
            })
        },
        generateHTML : function(_audience, num){
            var _tr = '<tr>'
            + '<td>' + num + '</td>'
            + '<td><botton class="btn btn-link view-audience">' + _audience.name + '</botton></td>'
            + '<td>' + (_audience.accountName ? _audience.accountName : _audience.fbAccountId) + '</td>'
            + '<td>' + (_audience.potentialUser ? Kit.toThousands(_audience.potentialUser) : 0) + '</td>';

            if (!_audience.updateTime){
                _updateTime = '--';
            } else{
                var timezoneValue = window.sessionStorage.timezoneValue;
                _updateTime = moment(_audience.updateTime).utcOffset(timezoneValue).format('YYYY-MM-DD HH:mm');
            }
            _tr +=  '<td>' + _updateTime + '</td>';
            var _tre = $(_tr);
            _tre.data("audience", _audience);
            return _tre;
        }
    }

    return audienceManager;
})
